//
//  ImageLibViewController.m
//  ImagePickerTest
//
//  Created by iptv-macmini on 2020/10/23.
//

#import "ImageLibViewController.h"

@interface ImageLibViewController () <UICollectionViewDelegate,UICollectionViewDataSource>
//collection容器
@property (nonatomic, strong)UICollectionView *collectionView;
//CellId
@property (nonatomic, copy)NSString *cellReuseIdentifier;
//collection布局
@property (nonatomic, strong)UICollectionViewFlowLayout *layout;
@property (nonatomic, strong)NSMutableArray *fetchResultArr;
//@property (nonatomic, strong)PHFetchResult *fetchList;
@end

@implementation ImageLibViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.collectionView];
    self.fetchResultArr = [[NSMutableArray alloc] init];
    
    PHFetchResult *fetchResult = [PHAsset fetchAssetsWithOptions:nil];
    if (fetchResult.count > 0) {
        PHFetchOptions *option = [[PHFetchOptions alloc] init];
        //ascending 为YES时，按照照片的创建时间升序排列;为NO时，则降序排列
        option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
        PHFetchResult *imgFetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:option];
        [self.fetchResultArr addObject:imgFetchResult];
    }
    [self.collectionView reloadData];
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.layout];
        [_collectionView setBackgroundColor:[UIColor whiteColor]];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        self.cellReuseIdentifier = @"cellReuseIdentifier";
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:self.cellReuseIdentifier];
    }
    return _collectionView;
}

- (UICollectionViewFlowLayout *)layout
{
    if (!_layout) {
        _layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat margin = 5.0f;
        _layout.sectionInset = UIEdgeInsetsMake(margin, margin, 0, margin);
        _layout.minimumLineSpacing = 5.0f;
        _layout.minimumInteritemSpacing = 5.0f;
        _layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _layout.itemSize = CGSizeMake((CGRectGetWidth(self.view.bounds)-25)/4, (CGRectGetWidth(self.view.bounds)-25)/4);
    }
    return _layout;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.fetchResultArr.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    PHFetchResult *imgFetchResult = [self.fetchResultArr objectAtIndex:section];
    return imgFetchResult.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:self.cellReuseIdentifier forIndexPath:indexPath];
    
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.synchronous = true;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    options.networkAccessAllowed = YES;
    PHFetchResult *imgFetchResult = [self.fetchResultArr objectAtIndex:indexPath.section];
    [[PHImageManager defaultManager] requestImageDataAndOrientationForAsset:[imgFetchResult objectAtIndex:indexPath.row] options:options resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, CGImagePropertyOrientation orientation, NSDictionary * _Nullable info)
    {
        UIImageView *imageView = [cell.contentView viewWithTag:100];
        if (!imageView) {
            imageView = [[UIImageView alloc] initWithFrame:cell.bounds];
            [cell.contentView addSubview:imageView];
        }
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.image = [UIImage imageWithData:imageData];
        imageView.layer.masksToBounds = YES;
    }];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    
}
@end
